home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7244 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  54 lines

  1. Path: dharma.hip.berkeley.edu!user
  2. From: genecutl@mendel.berkeley.edu (gc)
  3. Newsgroups: comp.lang.c
  4. Subject: basic question about pointers and local vars
  5. Date: 16 Feb 1996 18:18:18 GMT
  6. Organization: worl domination
  7. Message-ID: <genecutl-1602961021230001@dharma.hip.berkeley.edu>
  8. NNTP-Posting-Host: dharma.hip.berkeley.edu
  9. X-Newsreader: Value-Added NewsWatcher 2.0d31h+
  10.  
  11. This is basic and I should know it but I don't.  Here's my query--
  12. So I know that if you have:
  13.  
  14. main () {
  15. char string[10];
  16. function(string);
  17. ...
  18. }
  19. function (char *string) {
  20.    string[0] = 'a';
  21.    string[1] = 'b';
  22.    ....
  23. }
  24.  
  25. This changes what the string is in main because string is a pointer.  But
  26. what is the
  27. standard way to get a string returned by a function if you don't want to
  28. allocate
  29. space for the array in main.  For example, is this valid:
  30.  
  31. main() {
  32. char *string;
  33. function(string);
  34. ...
  35. }
  36. function(char *string) {
  37.    string = (char *)malloc(...);
  38.    string[0] = 'a';
  39.    string[1] = 'b';
  40. }
  41.  
  42. It doesn't seem like it should be because the value of the pointer itself
  43. gets changed
  44. here and I would have thought that that gets lost when control goes back
  45. to main, but
  46. it does work when I try it.  So where is the problem and what is the right
  47. way to do this?
  48. Thanks.
  49.  
  50. --Gene Cutler
  51.   genecutl@sp1.berkeley.edu
  52.   TheRoadToNoWhere
  53.   http://sp1.berkeley.edu/
  54.